import {
    DesktopOutlined,
    FileOutlined,
    PieChartOutlined,
    TeamOutlined,
    UserOutlined,
} from '@ant-design/icons';

import type { MenuProps } from 'antd';
import { Menu } from 'antd';
import { useNavigate, useLocation } from 'react-router-dom';
import { useState } from 'react';

type MenuItem = Required<MenuProps>['items'][number];

function getItem(
    label: React.ReactNode,
    key: React.Key,
    icon?: React.ReactNode,
    children?: MenuItem[],
): MenuItem {
    return {
        key,
        icon,
        children,
        label,
    } as MenuItem;
}

const items: MenuItem[] = [
    getItem('首页', '/page1', <PieChartOutlined />),
    getItem('页面2', '/page2', <DesktopOutlined />),
    getItem('栏目3', '/page3', <UserOutlined />, [
        getItem('栏目4', '/pages3/page301'),
        getItem('栏目5', '4'),
        getItem('栏目6', '5'),
    ]),
    getItem('Team', '/page4', <TeamOutlined />, [getItem('Team 1', '6'), getItem('Team 2', '8')]),
    getItem('Files', '9', <FileOutlined />),
];

// submenu keys of first level
const rootSubmenuKeys = ['/page3', '/page4'];


const Comp = () => {
    const curRouterName = useLocation();
    const navigate = useNavigate();
    let firtsKey: string = '';
    // 处理进入页面第一项选中的问题
    function handlerFn() {
        function findKey(obj:{key:string}) {
            return obj.key == curRouterName.pathname
        }

        for(let i = 0; i < items.length; i++){
            if(items[i]!['children'] && items[i]!['children'].length && items[i]!['children'].find(findKey)){
                firtsKey = items[i]!.key as any;
                break;
            }
        }
    }
    handlerFn();




    const [openKeys, setOpenKeys] = useState([firtsKey]);
    
    

    const onOpenChange: MenuProps['onOpenChange'] = keys => {
        const latestOpenKey = keys.find(key => openKeys.indexOf(key) === -1);
        if (rootSubmenuKeys.indexOf(latestOpenKey!) === -1) {
            setOpenKeys(keys);
        } else {
            setOpenKeys(latestOpenKey ? [latestOpenKey] : []);
        }
    };

    // 侧边栏点击事件
    const menuClick = (e: { key: string }) => {
        console.log(e.key);
        navigate(e.key)
    }

    return (
        < Menu theme="dark" defaultSelectedKeys={[curRouterName.pathname]} mode="inline" items={items} onClick={menuClick} openKeys={openKeys} onOpenChange={onOpenChange} />
    )
}

export default Comp